package common.network;

import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Properties;

import common.log.WindLog;
import common.props.ProjProps;

public abstract class BasicURL implements URLInterface {

	// TODO: implementare il Proxy
	// TODO: implentare il popup Authenticator per user/pass Proxy

	protected URL myURL;
	private String proxyuser=null;
	private String proxypwd=null;

	public BasicURL(String aUrl) throws MalformedURLException {
		try {
			setProxy();
		} catch (IOException e) {
			WindLog.getLogger().logSevere("Setting Proxy: " + e.getMessage());
		}
		myURL = new URL(aUrl);
	}

	public URL getMyURL() {
		return myURL;
	}

	public abstract ArrayList<String> getContent() throws Exception;

	// private void setProxy() throws IOException{
	// String proxyUrl;
	// proxyUrl = ProjProps.getProp(ProjProps.PROXY_URL);
	// if(proxyUrl!=null && !proxyUrl.equals("")){
	// Socket aSock = new Socket(ProjProps.getProp(ProjProps.PROXY_URL), new
	// Integer(ProjProps.getProp(ProjProps.PROXY_PORT)).intValue());
	// myProxy = new Proxy(Proxy.Type.HTTP, aSock.getRemoteSocketAddress());
	//			
	// }
	// }

	private void setProxy() throws IOException {

		String proxyUrl = ProjProps.getProp(ProjProps.PROXY_URL);

		if (proxyUrl != null && !proxyUrl.equals("")) {
			Properties systemSettings = System.getProperties();
			systemSettings.put("http.proxyHost", ProjProps
					.getProp(ProjProps.PROXY_URL));
			systemSettings.put("http.proxyPort", ProjProps
					.getProp(ProjProps.PROXY_PORT));
			
			proxyuser = ProjProps.getProp(ProjProps.PROXY_USER);
			proxypwd =  ProjProps.getProp(ProjProps.PROXY_PWD);
			
			if (proxyuser.equals("") || proxypwd.equals("")){
				//TODO: da dare popup recupero password
			}
			
			System.getProperties().put("http.proxyUser", proxyuser);
			System.getProperties().put("http.proxyPassword", proxypwd);

//			Authenticator.setDefault(new Authenticator() {
//				protected PasswordAuthentication getPasswordAuthentication() {
//					try {
//						return new PasswordAuthentication(ProjProps.getProp(ProjProps.PROXY_USER),
//								ProjProps.getProp(ProjProps.PROXY_PWD).toCharArray());
//					} catch (IOException e) {
//						//TODO: e.printStackTrace();
//						return null;
//					}
//				}
//			});
		}
	}
}
